package com.example.bbs.utils;

import com.example.bbs.model.User;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * author: VC
 * create: 2021/7/9 15:10
 * version: 1.0.0
 */
public class ServletUtils {
    public static void writeJavaScript(HttpServletResponse response, String script) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.getWriter().write("<script>" + script + "</script>");
    }

    public static User getLoginUser(HttpSession session) {
        Object obj = session.getAttribute("loginUser");
        if (obj == null) {
            return null;
        }
        if (obj instanceof User) {
            return (User) obj;
        }
        session.removeAttribute("loginUser");
        return null;
    }

    public static User getLoginUser(HttpSession session, HttpServletResponse response) throws IOException {
        User user = getLoginUser(session);
        if (user == null) {
            session.setAttribute("fail", "请先登录");
            response.sendRedirect("/login.jsp");
            return null;
        }
        return user;
    }
}
